//
//  AitContactManagerTool.m
//  Messenger
//
//  Created by jiangchao on 2018/11/19.
//  Copyright © 2018年 YN-APP-iOS. All rights reserved.
//
//艾特@功能管理类



#import "AitContactManagerTool.h"
#import "YNMessage.h"
#import "YNUser.h"
#import "YNManyPeopleChat.h"
#import "YNRecentChatObejct.h"
#import "YNMessagerReceiveHandle.h"
#import "YNContactManager.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"

@interface AitContactManagerTool()
{
    
}


/**
 *  @艾特  群，讨论组，项目组。用户名键值对
 key:[/@所有人] value: @所有人
 */
@property(nonatomic,strong)NSMutableDictionary * groupUserNameDic;


/**
 *  @艾特功能   群，讨论组，项目组。用户名键值对
 key:@所有人  value: [/@所有人]
 */
@property(nonatomic,strong)NSMutableDictionary * groupUserNameAitDic;




@end

@implementation AitContactManagerTool


-(NSMutableDictionary *)groupUserNameDic
{
    if(_groupUserNameDic == nil)
    {
        _groupUserNameDic = [NSMutableDictionary dictionary];
        [_groupUserNameDic setValue:@"@所有人 "forKey:@"@所有人"];
        [YNMessagerReceiveHandle getCurrentMessageChatTypemanyPeopleChatWith:self.groupNo];
        NSArray * userArray = [YNContactManager queryUserByGroupName:self.groupNo isAdmin:NO onlyGetTeachers:NO];
        for (YNUser * user in userArray) {
            NSString * userValue = [NSString stringWithFormat:@"@%@ ",user.userName];
            NSString * userKey = [NSString stringWithFormat:@"@%@",user.userName];
            [_groupUserNameDic setValue:userValue forKey:userKey];
        }
    }
    return _groupUserNameDic;
}
-(NSMutableDictionary *)groupUserNameAitDic
{
    if(_groupUserNameAitDic == nil)
    {
        _groupUserNameAitDic = [NSMutableDictionary dictionary];
        [_groupUserNameAitDic setValue:@"[/@所有人]" forKey:@"@所有人 "];
        for (YNUser * user in self.group.memberArray) {
            NSString * userKey = [NSString stringWithFormat:@"@%@ ",user.userName];
            NSString * userValue = [NSString stringWithFormat:@"[/@%@]",user.userName];
            [_groupUserNameAitDic setValue:userValue forKey:userKey];
        }
    }
    return _groupUserNameAitDic;
}

-(NSMutableDictionary *)aitContactMarkDic
{
    if(_aitContactMarkDic == nil)
    {
        _aitContactMarkDic = [NSMutableDictionary dictionary];
        //2018-11-20jc添加，获取数据库中保存的@艾特联系人，添加到字典中
        if(![YNIMTool isEmptyObject:self.group] && ![YNIMTool isEmptyString:self.group.groupName])
        {
            NSArray * array = [YNContactManager queryRecentChatWithUserNo:self.group.groupName];
            if(![YNIMTool isEmptyArray:array])
            {
                YNRecentChatObejct * recentChat = array.firstObject;
                if(![YNIMTool isEmptyString:recentChat.aitContactMarkArray])
                {
                    
                    NSDictionary  * recentChatDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:recentChat.aitContactMarkArray];
                    
                    [_aitContactMarkDic addEntriesFromDictionary:recentChatDic];
                }
            }
        }
    }
    return _aitContactMarkDic;
}



/**
 替换text  [\@张三] -> @张三

 @param text text
 @return 返回结果
 */
-(NSString *)replaceMessageTextWithText:(NSString *)text
{
    
    if([YNIMTool findAllMatchedText:text rexStr:kATRegularReturn].count >0 && [YNMessagerReceiveHandle getCurrentMessageChatTypemanyPeopleChatWith:self.groupNo] != 0)
    {
        
        NSArray * userAllKey = self.groupUserNameDic.allKeys;
        for (int i = 0; i< userAllKey.count; i++) {
            NSString * userKey = userAllKey[i];
            if([text containsString:userKey])
            {
                NSString * userValue = [self.groupUserNameDic objectForKey:userKey];
               
                
                NSString * userKey1 = [NSString stringWithFormat:@"[/%@]",userKey];
                NSString * userKey2 = [NSString stringWithFormat:@"[\\/%@]",userKey];
                text = [text stringByReplacingOccurrencesOfString:userKey1 withString:userValue];
                text = [text stringByReplacingOccurrencesOfString:userKey2 withString:userValue];
                
                
            }
        }
        
    }
    
    return text;
}


/**
 替换message的text和body [\@张三] -> @张三

 @param message message消息
 @return 返回结果
 */
-(YNMessage*)replaceMessageTextWithMessage:(YNMessage*)message
{
    YNMessage * ynMessage = (YNMessage *)message;
    if([YNIMTool findAllMatchedText:message.body rexStr:kATRegularReturn].count >0 && [YNMessagerReceiveHandle getCurrentMessageChatTypemanyPeopleChatWith:self.groupNo] != 0)
    {
        NSString * text = [ynMessage.text mutableCopy];
        NSString * body = [ynMessage.body mutableCopy];
       
        NSArray * userAllKey = self.groupUserNameDic.allKeys;
        for (int i = 0; i< userAllKey.count; i++) {
            NSString * userKey = userAllKey[i];
            if([body containsString:userKey])
            {
                NSString * userValue = [self.groupUserNameDic objectForKey:userKey];
                NSString * userKey1 = [NSString stringWithFormat:@"[/%@]",userKey];
                NSString * userKey2 = [NSString stringWithFormat:@"[\\/%@]",userKey];
                text = [text stringByReplacingOccurrencesOfString:userKey1 withString:userValue];
                body = [body stringByReplacingOccurrencesOfString:userKey1 withString:userValue];
                text = [text stringByReplacingOccurrencesOfString:userKey2 withString:userValue];
                body = [body stringByReplacingOccurrencesOfString:userKey2 withString:userValue];
            }
        }
        ynMessage.text = text;
        ynMessage.body = body;
        
    }
    YNMessage* returnMessage =ynMessage;
    return returnMessage;
}


/**
 删除 @张三
 
 @param textView
 @param range
 @return
 */
-(BOOL)removeAitTextView:(UITextView *)textView text:(NSString *)text range:(NSRange)range
{
    // 判断删除的是一个@中间的字符就整体删除
    if([textView.text containsString:@"@"])
    {
        NSMutableString *string = [NSMutableString stringWithString:textView.text];
        NSString * aitContactStr ;
        NSArray *matches = [AitContactManagerTool findAllAtText:textView.text];

        BOOL inAt = NO;
        NSInteger index = range.location;
        for (NSTextCheckingResult *match in matches)
        {
            NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
            if (NSLocationInRange(range.location, newRange))
            {

                index = match.range.location;
                aitContactStr = [string substringWithRange:match.range];
                NSString * aitValue = [self.groupUserNameAitDic objectForKey:aitContactStr];
                if(![YNIMTool isEmptyString:aitValue])
                {
                    inAt = YES;
                    [string replaceCharactersInRange:match.range withString:@""];
                }

                break;
            }
        }

        if (inAt)
        {
            textView.text = string;
            NSString * aitStr = [self.aitContactMarkDic objectForKey:aitContactStr];
            if(![YNIMTool isEmptyString:aitContactStr] && ![YNIMTool isEmptyString:aitStr])
            {
                [self.aitContactMarkDic removeObjectForKey:aitContactStr];

            }
            textView.selectedRange = NSMakeRange(index, 0);
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else
    {
        return NO;
    }
    return NO;
}

/**
 获取text值

 @param inputText
 @param chatType
 @return
 */
-(NSString *)getInputViewTextWithinputText:(NSString*)inputText chatType:(int)chatType
{
    NSString * text = inputText;
    //2018-11-14JC添加，解析@艾特 字符串。  @张三 -> [/@张三]
    if(chatType != 0 && [AitContactManagerTool findAllAtText:text].count >0 && ![YNIMTool isEmptyDictionary:self.aitContactMarkDic])
    {
        NSArray * userAllKey = self.aitContactMarkDic.allKeys;
        for (int i = 0; i< userAllKey.count; i++) {
            NSString * userKey = userAllKey[i];
            NSString * aitStr = [self.aitContactMarkDic objectForKey:userKey];
            NSString * groupDicStr = [self.groupUserNameAitDic objectForKey:userKey];
            if([text containsString:userKey] && ![YNIMTool isEmptyString:aitStr] && ![YNIMTool isEmptyString:groupDicStr])
            {
                
                NSString * userValue = [self.groupUserNameAitDic objectForKey:userKey];
                text = [text stringByReplacingOccurrencesOfString:userKey withString:userValue];
            }
        }
    }
    //发送后，清空数据
    [self.aitContactMarkDic removeAllObjects];
    return text;
}

/**
 2018-11-15JC添加，增加艾特@功能的判断。
 aitContactMark = 0 默认没有@谁，1：@个人,2:@所有人
 @param manyPeopleChat
 @param groupType
 */
+(void)setAitContactMarkManyPeopleChat:(YNManyPeopleChat*)manyPeopleChat groupType:(int)groupType
{
    manyPeopleChat.aitContactMark = 0;
    //判断是否有[\@张三]格式的数据没
    NSArray * chatArray = [YNIMTool findAllMatchedText:manyPeopleChat.content rexStr:kATRegularReturn];
    YNMessage * message = [[YNMessage alloc]init];
    message.friendId = manyPeopleChat.groupNo;
    //不在聊天界面时，才给艾特提示
    if(![AitContactManagerTool currentChatVC:message] && ![YNIMTool isEmptyArray:chatArray])
    {
        //判断是否有艾特所有人
        if([manyPeopleChat.content containsString:@"[/@所有人]"])
        {
            manyPeopleChat.aitContactMark = 2 ;
        }
        //判断是否有艾特个人的没，艾特个人的权限比艾特所有人的大
        NSString * userKey = [NSString stringWithFormat:@"[/@%@]",[YNIMmanager sharedInstance].userName];
        if([manyPeopleChat.content containsString:userKey])
        {
            manyPeopleChat.aitContactMark = 1;
        }
    }
}

/**
 用于联系人列表：[/@所有人]->@所有人。
 @param manyPeopleChat
 */
+(void)setAitContactMarkManyPeopleChat:(YNRecentChatObejct*)recentChat
{
    CurrenChatObjType chatType = [YNMessagerReceiveHandle getCurrentMessageChatTypemanyPeopleChatWith:recentChat.userNo];
    if(chatType != 0)
    {
        //判断是否有[\@张三]格式的数据没
        NSArray * chatArray = [YNIMTool findAllMatchedText:recentChat.content rexStr:kATRegularReturn];
        if(![YNIMTool isEmptyArray:chatArray])
        {
            //判断是否有艾特@所有人
            NSArray *userArray = [YNContactManager  queryUserByGroupName:recentChat.userNo isAdmin:NO onlyGetTeachers:NO];
            if([recentChat.content containsString:@"[/@所有人]"] ||  [recentChat.content containsString:@"[\\/@所有人]"])
            {
                recentChat.text= [recentChat.text stringByReplacingOccurrencesOfString:@"[/@所有人]" withString:@"@所有人"];
                recentChat.content= [recentChat.content stringByReplacingOccurrencesOfString:@"[/@所有人]" withString:@"@所有人"];
                recentChat.text= [recentChat.text stringByReplacingOccurrencesOfString:@"[\\/@所有人]" withString:@"@所有人"];
                recentChat.content= [recentChat.content stringByReplacingOccurrencesOfString:@"[\\/@所有人]" withString:@"@所有人"];
            }
            //判断是否有艾特@个人的没，艾特@个人的权限比艾特@所有人的大
            for (YNUser * user in userArray) {
                NSString * userKey1 = [NSString stringWithFormat:@"[/@%@]",user.userName];
                NSString * userKey2 = [NSString stringWithFormat:@"[\\/@%@]",user.userName];
                if([recentChat.content containsString:userKey1] || [recentChat.content containsString:userKey2])
                {
                    recentChat.text = [recentChat.text stringByReplacingOccurrencesOfString:userKey1 withString:[NSString stringWithFormat:@"@%@",user.userName]];
                    recentChat.content = [recentChat.content stringByReplacingOccurrencesOfString:userKey1 withString:[NSString stringWithFormat:@"@%@",user.userName]];
                    recentChat.text = [recentChat.text stringByReplacingOccurrencesOfString:userKey2 withString:[NSString stringWithFormat:@"@%@",user.userName]];
                    recentChat.content = [recentChat.content stringByReplacingOccurrencesOfString:userKey2 withString:[NSString stringWithFormat:@"@%@",user.userName]];
                }
                NSArray * chatArray = [YNIMTool findAllMatchedText:recentChat.content rexStr:kATRegularReturn];
                if([YNIMTool isEmptyArray:chatArray])
                {
                    break;
                }
                
            }
        }
    }
}

//判断当前是否是好友聊天界面
+(BOOL)currentChatVC:(YNMessage *)message
{
    NSString *userNo = [[YNIMmanager sharedInstance]getIdCurrChatWithUser];
    if ([userNo isEqualToString:message.friendId])
    {
        return YES;
    }
    return NO;
}
/**
 筛选艾特@符号
 @张三
 
 @return
 */
+(NSArray<NSTextCheckingResult *> *)findAllAtText:(NSString *)text
{
    // 找到文本中所有的@
    if([YNIMTool isEmptyString:text])
    {
        return nil;
    }
    NSString *string = text;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kATRegular options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}



@end
